<script setup lang="ts">
import type { ApiApi } from '#/api/system/api';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { ElMessage } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { createApi, getApi, updateApi } from '#/api/system/api';

import { useApiFormSchema } from '../data';

const emit = defineEmits(['success']);

const formData = ref<ApiApi.Api>();
const getTitle = computed(() => {
  return formData.value?.id ? $t('ui.api.update') : $t('ui.api.create');
});

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    drawerApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as ApiApi.Api;
    try {
      await (formData.value?.id ? updateApi(data) : createApi(data));
      // 关闭并提示
      await drawerApi.close();
      emit('success');
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      drawerApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    const data = drawerApi.getData<ApiApi.Api>();
    if (!data) {
      return;
    }

    // 如果有 systemId 但没有 id，说明是新建
    if (data.systemId && !data.id) {
      formData.value = { ...data };
      await formApi.setValues(formData.value);
      return;
    }

    // 如果有 id，说明是编辑，需要加载详情
    if (data.id) {
      drawerApi.lock();
      try {
        formData.value = await getApi(data.id as number);
        // 设置到 values
        await formApi.setValues(formData.value);
      } finally {
        drawerApi.unlock();
      }
    }
  },
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useApiFormSchema(),
  showDefaultActions: false,
});
</script>

<template>
  <Drawer
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="w-1/3"
    :title="getTitle"
  >
    <Form />
  </Drawer>
</template>

<style scoped></style>
